package com.example.controller;

import com.alibaba.excel.EasyExcel;
import com.example.easyExcelListener.ReportDataListener;
import com.example.entity.ReportData;
import com.example.entity.vo.DetailDTO;
import com.example.service.ReportDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author ZHAO Yudong
 * @Date 2020/11/17 11:01
 * @description：风控数据
 */
@RestController
@Api(description = "风控数据")
@RequestMapping("/report")
public class ReportController {

    @Autowired
    private ReportDataService reportDataService;


    @ApiOperation(value = "上传excel")
    @PostMapping("/upload")
    public String upload(@Param("file") MultipartFile file) throws IOException {
        if (file != null) {
            EasyExcel.read(file.getInputStream(), ReportData.class, new ReportDataListener(reportDataService)).sheet().doRead();
            return "success";
        } else {
            return "file 为 null";
        }
    }

    @ApiOperation(value = "下载excel")
    @PostMapping("/downloadFailedUsingJson")
    public void downloadFailedUsingJson(HttpServletResponse response, @RequestBody List<DetailDTO> details) throws IOException {


        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), DetailDTO.class).sheet("模板").doWrite(details);
    }
}
